package logic

import (
	"context"
	"errors"
	"login-mgr/models/cache"
	"login-mgr/pkg"
	"math/rand"
	"strconv"
	"time"

	"login-mgr/loginrpc/internal/svc"
	"login-mgr/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *loginrpc.SendSmsRequest) (*loginrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	
	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New("短信验证码发送失败")
	}
	cache.Rdb.Set(l.ctx, "sendSms"+in.Phone, code, time.Minute*3)

	return &loginrpc.SendSmsResponse{}, nil
}
